package com.itheima.reggie.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> findAll() {
       return categoryMapper.findAll();
    }

    @Override
    public void save(Category category) {
        //其他变量初始化
        category.setId(IdUtil.getSnowflake(1,1).nextId());
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
//        category.setUpdateUser(1L);
//        category.setUpdateTime(new Date());
        categoryMapper.updateById(category);
    }
    //删除菜品 首先要判断要删除的种类下是否有菜品
    @Override
    public ResultInfo delete(Long id) {
        //通过id查找菜品数量
        int count1 = categoryMapper.findCountToDish(id);
        if (count1 > 0) {
           // return ResultInfo.error("不能删");
            throw new CustomException("还有菜品，不能删除");
        }
        //通过id查找套餐数量
        int count2 = categoryMapper.findCountToSetmeal(id);
        if (count2 > 0) {
            //return ResultInfo.error("不能删");
            throw new CustomException("还有套餐，不能删除");
        }
        //删除
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }

    @Override
    public List<Category> findList(Integer type) {
        //定义个一个type 判断 实现菜品种类回显
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        List<Category> categoryList = categoryMapper.selectList(wrapper);
        return categoryList;
    }
}
